#ifndef _PIDMAN_HPP
#define _PIDMAN_HPP 1

#define PID_MIN_BOUND 300
#define PID_MAX_BOUND 5000

#include<cstdlib>
#include<cstring>
#include<iostream>

int allocate_map();
int allocate_pid();
void release_pid(int pid);

class PIDMan final{
    public:
        constexpr static int PID_MIN = 300;
        constexpr static int PID_MAX = 5000;
        static PIDMan& allocate_map()noexcept{
            // if(!alloc){
            //     alloc=new PIDMan();
            //     memset(alloc->pidMap,0,sizeof(alloc->pidMap));
            // }
            return PIDMan::Instance();
        }
        static int allocate_pid()noexcept{// -1 for error
            int pid=-1;
            PIDMan& temp=PIDMan::Instance();
            for (size_t i = 0; i < PID_MAX-PID_MIN; ++i){
                if(!temp.pidMap[i]){
                    pid=i+PID_MIN;
                    temp.pidMap[i]=true;
                    break;
                }
            }
            return pid;
        }
        static void release_pid(int pid){
            PIDMan&temp=PIDMan::Instance();
            if(PidValidate(pid))
                temp.pidMap[pid]=false;
        }
        static bool PidValidate(int pid){
            return pid>=PID_MIN&&pid<=PID_MAX;
        }
        static PIDMan& Instance()noexcept{
            static PIDMan alloc;
            return alloc;
        }
    private:
        bool pidMap[PID_MAX-PID_MIN];
        // static PIDMan *alloc;
        PIDMan(){
            memset(pidMap,0,sizeof(pidMap));
        }
        PIDMan(PIDMan const&);
        ~PIDMan(){}
};
int allocate_map(){}
int allocate_pid(){
    int p=PIDMan::allocate_pid();
    std::cout<<"allocate pid : "<<p<<std::endl;
    return p;
}
void release_pid(int pid){
    std::cout<<"release pid : "<<pid<<std::endl;
    PIDMan::release_pid(pid);
}

#endif//PIDMAN_HPP
